#include "mytcpserver.h"
#include <QDebug>
#include <QMessageBox>
#include <QHostAddress>
#include <QFile>
#include <QWidget>

MyTcpServer::MyTcpServer() {

}

MyTcpServer &MyTcpServer::getInstance()
{
    static MyTcpServer instance;
    return instance;
}

void MyTcpServer::incomingConnection(qintptr socketDescriptor)
{
    qDebug() << "server: new connect";
    MyTcpSocket* sock = new MyTcpSocket;
    sock->setSocketDescriptor(socketDescriptor);
    m_sock_hash.insert(sock, 0);

    //当接受到关闭信号时:
    connect(sock, &MyTcpSocket::logout, this, [&](MyTcpSocket* socket) {
        //打印测试
        // QHash<MyTcpSocket*, int>::const_iterator i = m_sock_hash.constBegin();
        // while (i != m_sock_hash.constEnd()) {
        //     qDebug() << i.key()->m_name << ": " << i.value() << Qt::endl;
        //     ++i;
        // }
        //qDebug() << "reomve后:---------------------------------------------------";

        m_sock_hash.remove(socket);
    });
}

void MyTcpServer::resend(const char *user_name, PDU *pdu)
{
    if (!user_name || !pdu) return;
    // qDebug() << "resend";
    QHash<MyTcpSocket*, int>::const_iterator i = m_sock_hash.constBegin();
    while (i != m_sock_hash.constEnd()) {
        // qDebug() << i.key()->m_name;
        if (i.key()->m_name == user_name) {
            i.key()->write((char*)pdu, pdu->uiPDULen);
            // pdu->printPDU();
            break;
        }
        ++i;
    }
}



